package gold.digger;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC390 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int lastRemaining(int n) {
            if (n == 1) return 1;
            if (n == 2) return 2;
            if (n == 3) return 2;
            if (n == 4) return 2;

            int step = 1, count = n, start = 1, end = n;
            boolean forwardFlag = true;
            while (count > 1) {
                if (forwardFlag) {
                    //正向筛选
                    start += step;
                    if (count % 2 != 0) end -= step;//看是否保留末尾
                } else {
                    //逆向筛选
                    end -= step;
                    if (count % 2 != 0) start += step;//看是否保留末尾
                }

                count /= 2;
                step *= 2;
                forwardFlag = !forwardFlag;
            }

            return start;
        }
    }

    public void run() {
        Solution solution = new Solution();
        for (int i = 1; i < 13; i++) {
            System.out.println(i + " : " + solution.lastRemaining(i));
        }
    }

    public static void main(String[] args) throws Exception {
        LC390 an = new LC390();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
